package com.android.clinic.doctors.app.ui.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.clinic.doctors.app.ClinicDoctorsApplication;
import com.android.clinic.doctors.app.R;
import com.android.clinic.doctors.app.base.BaseFragment;
import com.android.clinic.doctors.app.glide.ImageLoaderUtils;
import com.android.clinic.doctors.app.http.HttpClient;
import com.android.clinic.doctors.app.ui.EditPlacardActivity;
import com.android.clinic.doctors.app.ui.inquiry.GraphicInquiryListActivity;
import com.android.clinic.doctors.app.ui.patient.PatientListActivity;
import com.android.clinic.doctors.app.utils.AppApplicationManager;
import com.qiangxi.checkupdatelibrary.dialog.UpdateDialog;
import com.qiangxi.checkupdatelibrary.utils.ApplicationUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.qiangxi.checkupdatelibrary.dialog.UpdateDialog.UPDATE_DIALOG_PERMISSION_REQUEST_CODE;

/**
 * 首页
 * Created by cheng on 2018/6/11.
 */
public class HomeFragment extends BaseFragment {

    private String[] arrayString;
//    private int[] arrayImages = {R.drawable.icon_home_edit_placard, R.drawable.icon_home_patient,
//        R.drawable.icon_home_graphic_inquiry, R.drawable.icon_home_setting_price};
private int[] arrayImages = {R.drawable.icon_home_edit_placard, R.drawable.icon_home_patient,
        R.drawable.icon_home_graphic_inquiry};

    private Intent intent;

    private UpdateDialog mUpdateDialog;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ImageView ivHomeUserHead = findViewById(R.id.iv_home_user_head);
        TextView tvHomeUserName = findViewById(R.id.tv_home_user_name);
        GridView homeGridView = findViewById(R.id.home_gridView);

        ImageLoaderUtils.getInstance().loadHeadImage(ClinicDoctorsApplication.getUserInfo().getImgUrl(), ivHomeUserHead);
        tvHomeUserName.setText(ClinicDoctorsApplication.getUserInfo().getName());

        arrayString = getResources().getStringArray(R.array.home_array);
        homeGridView.setAdapter(new HomeAdapter());
        homeGridView.setOnItemClickListener((parent, view, position, id) -> {
            switch (position) {
                // 编辑公告
                case 0:
                    intent = new Intent(mActivity, EditPlacardActivity.class);
                    startActivity(intent);
                    break;
                // 患者
                case 1:
                    intent = new Intent(mActivity, PatientListActivity.class);
                    startActivity(intent);
                    break;
                // 图文问诊
                case 2:
                    intent = new Intent(mActivity, GraphicInquiryListActivity.class);
                    startActivity(intent);
                    break;
//                // 价格设置
//                case 3:
//                    intent = new Intent(mActivity, SettingPriceActivity.class);
//                    startActivity(intent);
//                    break;
                default:break;
            }
        });

        checkVersionUpdate();

    }

    private class HomeAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return arrayString.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (null == convertView) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.item_grid_home, null);
                holder = new ViewHolder();
                holder.ivItemIcon = convertView.findViewById(R.id.iv_home_item_icon);
                holder.tvItemName = convertView.findViewById(R.id.tv_home_item_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tvItemName.setText(arrayString[position]);
            holder.ivItemIcon.setImageResource(arrayImages[position]);
            return convertView;
        }

        class ViewHolder {
            ImageView ivItemIcon;
            TextView tvItemName;
        }
    }

    /**
     * 版本更新检测
     */
    private void checkVersionUpdate() {
        Call<ResponseBody> call = HttpClient.getHttpService().getVersion();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String result = response.body().string();
                    JSONObject json = new JSONObject(result);
                    String version = json.getString("version");
                    String url = json.getString("url");
                    String content = json.getString("content");
                    String updateTime = json.getString("updateTime");
                    String versionName = json.getString("versionName");

                    // 因为发布360市场的时候，上传的版本号是9位的，而其他市场是8位的；所以这里为了兼容，做了判断处理
                    String versionCode = String.valueOf(AppApplicationManager.getVersionCode(getActivity()));
                    if (versionCode.length() == 9) {
                        versionCode = versionCode.substring(0, versionCode.length() - 1);
                    }
                    if (!String.valueOf(versionCode).equals(version)) {
                        versionUpdate(url, content, updateTime, versionName);
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    /**
     * 版本更新对话框
     *
     * @param url
     * @param content
     * @param updateTime
     */
    private void versionUpdate(String url, String content, String updateTime, String versionName) {
        mUpdateDialog = new UpdateDialog(getActivity(), ((MainActivity) (getActivity())).getVisibleFragment());
        mUpdateDialog
                .setDownloadUrl(url)
                .setTitle(AppApplicationManager.getApplicationName(getActivity()) + "APP有更新了!")
                .setReleaseTime(updateTime)
                .setVersionName(versionName)
                .setUpdateDesc(content)
                .setFileName("doctor.apk")
                .setFilePath(Environment.getExternalStorageDirectory().getPath() + "/fucai")
                .setShowProgress(true)
                .setIconResId(R.mipmap.icon_app_logo)
                .setAppName(ApplicationUtil.getApplicationName(getActivity())).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == UPDATE_DIALOG_PERMISSION_REQUEST_CODE) {
                //进行下载操作
                if (mUpdateDialog != null) {
                    mUpdateDialog.download();
                }
            } else {
                //用户不同意,提示用户,如下载失败,因为您拒绝了相关权限
                Toast.makeText(getActivity(), getResources().getString(R.string.permission_need), Toast.LENGTH_SHORT).show();
            }
        }
    }

}
